from flask import render_template, request, redirect, url_for, flash
from datetime import datetime, time
from app import app, db
from app.models import Customer, Vehicle, Order, Part, OrderItem, User
import random
from flask_login import login_user, logout_user, login_required, current_user
from functools import wraps

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.has_role('admin'):
            flash('需要管理员权限', 'error')
            return redirect(url_for('index'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
        
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        remember = request.form.get('remember', False)
        
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            if not user.active:
                flash('账号已被禁用', 'error')
                return redirect(url_for('login'))
            
            login_user(user, remember=remember)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('index'))
        
        flash('用户名或密码错误', 'error')
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

# 用户管理路由
@app.route('/users')
@login_required
@admin_required
def users():
    users_list = User.query.all()
    return render_template('users.html', users=users_list)

@app.route('/add_user', methods=['POST'])
@login_required
@admin_required
def add_user():
    try:
        username = request.form.get('username')
        password = request.form.get('password')
        name = request.form.get('name')
        role = request.form.get('role')
        
        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'error')
            return redirect(url_for('users'))
        
        user = User(username=username, name=name, role=role)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        flash('用户添加成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('添加失败：' + str(e), 'error')
    
    return redirect(url_for('users'))

@app.route('/')
@login_required
def index():
    # 获取今天的开始和结束时间
    today_start = datetime.combine(datetime.today(), time.min)
    today_end = datetime.combine(datetime.today(), time.max)
    
    # 获取今日订单
    today_orders = Order.query.filter(
        Order.created_at.between(today_start, today_end)
    ).order_by(Order.created_at.desc()).all()
    
    # 获取订单状态统计
    order_stats = {
        'pending': Order.query.filter_by(status='待维修').count(),
        'in_progress': Order.query.filter_by(status='维修中').count(),
        'completed': Order.query.filter_by(status='已完成').count(),
        'cancelled': Order.query.filter_by(status='已取消').count()
    }
    
    # 获取基础统计数据
    stats = {
        'Customer': Customer,
        'Vehicle': Vehicle,
        'Order': Order,
        'Part': Part,
        'today_orders': today_orders,
        'order_stats': order_stats
    }
    
    return render_template('index.html', **stats)

@app.route('/orders')
@login_required
def orders():
    page = request.args.get('page', 1, type=int)
    per_page = 5  # 每页显示10条记录
    
    # 获取状态筛选参数
    status = request.args.get('status')
    
    # 根据状态筛选订单
    if status:
        pagination = Order.query.filter_by(status=status).order_by(Order.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False)
    else:
        pagination = Order.query.order_by(Order.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False)
        
    customers_list = Customer.query.all()
    vehicles_list = Vehicle.query.all()
    return render_template('orders.html', 
                         pagination=pagination,
                         orders=pagination.items,
                         customers=customers_list,
                         vehicles=vehicles_list,
                         current_status=status)

@app.route('/customers')
@login_required
def customers():
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = Customer.query.paginate(page=page, per_page=per_page, error_out=False)
    return render_template('customers.html', 
                         pagination=pagination,
                         customers=pagination.items)

@app.route('/vehicles')
@login_required
def vehicles():
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = Vehicle.query.paginate(page=page, per_page=per_page, error_out=False)
    customers_list = Customer.query.all()
    return render_template('vehicles.html', 
                         pagination=pagination,
                         vehicles=pagination.items,
                         customers=customers_list)

@app.route('/parts')
@login_required
def parts():
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = Part.query.paginate(page=page, per_page=per_page, error_out=False)
    return render_template('parts.html', 
                         pagination=pagination,
                         parts=pagination.items)

@app.route('/add_customer', methods=['POST'])
@login_required
def add_customer():
    try:
        name = request.form.get('name')
        phone = request.form.get('phone')
        
        new_customer = Customer(name=name, phone=phone)
        db.session.add(new_customer)
        db.session.commit()
        
        flash('客户添加成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('添加失败：' + str(e), 'error')
    
    return redirect(url_for('customers'))

@app.route('/add_part', methods=['POST'])
@login_required
def add_part():
    try:
        part_number = request.form.get('part_number')
        name = request.form.get('name')
        unit = request.form.get('unit')
        cost_price = float(request.form.get('cost_price'))
        price = float(request.form.get('price'))
        
        new_part = Part(
            part_number=part_number,
            name=name,
            unit=unit,
            cost_price=cost_price,
            price=price
        )
        db.session.add(new_part)
        db.session.commit()
        
        flash('配件添加成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('添加失败：' + str(e), 'error')
    
    return redirect(url_for('parts'))

@app.route('/add_order', methods=['POST'])
@login_required
def add_order():
    try:
        customer_id = request.form.get('customer_id')
        vehicle_id = request.form.get('vehicle_id')
        
        # 生成订单号 (年月日时分秒+4位随机数)
        order_number = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        
        new_order = Order(
            order_number=order_number,
            customer_id=customer_id,
            vehicle_id=vehicle_id,
            total_amount=0,  # 初始金额为0
            operator='系统'  # 可以根据实际登录用户设置
        )
        db.session.add(new_order)
        db.session.commit()
        
        flash('订单创建成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('创建失败：' + str(e), 'error')
    
    return redirect(url_for('orders'))

@app.route('/add_vehicle', methods=['POST'])
@login_required
def add_vehicle():
    try:
        model = request.form.get('model')
        plate_number = request.form.get('plate_number')
        notes = request.form.get('notes')
        customer_id = request.form.get('customer_id')
        
        new_vehicle = Vehicle(
            model=model,
            plate_number=plate_number,
            notes=notes,
            customer_id=customer_id
        )
        db.session.add(new_vehicle)
        db.session.commit()
        
        flash('车辆添加成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('添加失败：' + str(e), 'error')
    
    return redirect(url_for('vehicles'))

@app.context_processor
def utility_processor():
    return dict(flash=flash) 

@app.route('/customer/<int:id>')
def customer_detail(id):
    customer = Customer.query.get_or_404(id)
    return render_template('customer_detail.html', customer=customer) 

@app.route('/update_order_status', methods=['POST'])
def update_order_status():
    try:
        order_id = request.form.get('order_id')
        status = request.form.get('status')
        repair_notes = request.form.get('repair_notes')
        
        order = Order.query.get_or_404(order_id)
        order.status = status
        order.repair_notes = repair_notes
        
        if status == '已完成':
            order.completed_at = datetime.now()
        
        db.session.commit()
        flash('订单状态更新成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败：' + str(e), 'error')
    
    return redirect(url_for('orders')) 

@app.route('/edit_customer', methods=['POST'])
def edit_customer():
    try:
        customer_id = request.form.get('id')
        name = request.form.get('name')
        phone = request.form.get('phone')
        
        customer = Customer.query.get_or_404(customer_id)
        customer.name = name
        customer.phone = phone
        
        db.session.commit()
        flash('客户信息更新成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败：' + str(e), 'error')
    
    return redirect(url_for('customers'))

@app.route('/edit_vehicle', methods=['POST'])
def edit_vehicle():
    try:
        vehicle_id = request.form.get('id')
        model = request.form.get('model')
        plate_number = request.form.get('plate_number')
        notes = request.form.get('notes')
        customer_id = request.form.get('customer_id')
        
        vehicle = Vehicle.query.get_or_404(vehicle_id)
        vehicle.model = model
        vehicle.plate_number = plate_number
        vehicle.notes = notes
        vehicle.customer_id = customer_id
        
        db.session.commit()
        flash('车辆信息更新成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败：' + str(e), 'error')
    
    return redirect(url_for('vehicles'))

@app.route('/edit_part', methods=['POST'])
def edit_part():
    try:
        part_id = request.form.get('id')
        part_number = request.form.get('part_number')
        name = request.form.get('name')
        unit = request.form.get('unit')
        cost_price = float(request.form.get('cost_price'))
        price = float(request.form.get('price'))
        
        part = Part.query.get_or_404(part_id)
        part.part_number = part_number
        part.name = name
        part.unit = unit
        part.cost_price = cost_price
        part.price = price
        
        db.session.commit()
        flash('配件信息更新成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败：' + str(e), 'error')
    
    return redirect(url_for('parts')) 

@app.route('/edit_order', methods=['POST'])
def edit_order():
    try:
        order_id = request.form.get('id')
        customer_id = request.form.get('customer_id')
        vehicle_id = request.form.get('vehicle_id')
        status = request.form.get('status')
        repair_notes = request.form.get('repair_notes')
        
        order = Order.query.get_or_404(order_id)
        order.customer_id = customer_id
        order.vehicle_id = vehicle_id
        order.status = status
        order.repair_notes = repair_notes
        
        if status == '已完成':
            order.completed_at = datetime.now()
        
        db.session.commit()
        flash('订单信息更新成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('更新失败：' + str(e), 'error')
    
    return redirect(url_for('orders')) 

@app.route('/print_order/<int:id>')
@login_required
def print_order(id):
    order = Order.query.get_or_404(id)
    return render_template('print_order.html', order=order) 

@app.route('/order_items/<int:order_id>')
def order_items(order_id):
    order = Order.query.get_or_404(order_id)
    parts = Part.query.all()
    return render_template('order_items.html', order=order, parts=parts)

@app.route('/add_order_item', methods=['POST'])
def add_order_item():
    try:
        order_id = request.form.get('order_id')
        part_id = request.form.get('part_id')
        quantity = int(request.form.get('quantity'))
        
        part = Part.query.get_or_404(part_id)
        order = Order.query.get_or_404(order_id)
        
        # 计算金额
        amount = quantity * part.price
        
        # 创建订单项
        order_item = OrderItem(
            order_id=order_id,
            part_id=part_id,
            quantity=quantity,
            price=part.price,
            amount=amount
        )
        db.session.add(order_item)
        
        # 更新订单总金额
        order.total_amount = (order.total_amount or 0) + amount
        
        db.session.commit()
        flash('配件添加成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('添加失败：' + str(e), 'error')
    
    return redirect(url_for('order_items', order_id=order_id))

@app.route('/delete_order_item/<int:item_id>')
def delete_order_item(item_id):
    try:
        item = OrderItem.query.get_or_404(item_id)
        order_id = item.order_id
        order = Order.query.get(order_id)
        
        # 更新订单总金额
        order.total_amount -= item.amount
        
        db.session.delete(item)
        db.session.commit()
        flash('配件删除成功！', 'success')
    except Exception as e:
        db.session.rollback()
        flash('删除失败：' + str(e), 'error')
    
    return redirect(url_for('order_items', order_id=order_id)) 